﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JzSport.Model
{
    public class LocationService
    {
        /// <summary>
        /// 更新最新的位置信息
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="city"></param>
        /// <param name="longitude"></param>
        /// <param name="lattude"></param>
        /// <returns></returns>
        public ServiceResult<Location> UpdateLocation(int accountId,
            string city,
            double longitude,
            double lattude)
        {
            using (JzSportDbContext dbContext = new JzSportDbContext())
            {

                LocationRepository reps = new LocationRepository(dbContext);

                Location latestLocation = reps.GetLatest(accountId);
                if (latestLocation != null)
                {
                    latestLocation.IsLatest = false;
                    reps.Update(latestLocation.Id, latestLocation);
                }

                Location location = new Location();
                location.Id = Guid.NewGuid();
                location.AccountId = accountId;
                location.City = city;
                location.Longitude = longitude;
                location.CreatedTime = DateTime.Now;
                location.IsLatest = true;

                reps.Save(location);

                if (dbContext.SaveChanges() > 0)
                {
                    return new ServiceResult<Location>(ErrorCode.NoError, location);
                }
                return new ServiceResult<Location>(ErrorCode.DB_Error);
            }
        }
    }
}
